# -*- coding: utf-8 -*-
"""统计分析相关路由"""

from flask import Blueprint, request, jsonify
from flask_restx import Api, Resource, fields
from datetime import datetime, timedelta
import pandas as pd
import logging
from typing import Dict, List, Any

from database.db_service import get_statistics_data

logger = logging.getLogger(__name__)

# 创建蓝图
statistics_bp = Blueprint('statistics', __name__)
api = Api(statistics_bp, version='1.0', title='统计分析API', description='统计分析相关接口')

# 命名空间
statistics_ns = api.namespace('statistics', description='统计分析接口')

# 模型定义
alert_trend_model = api.model('AlertTrend', {
    'time': fields.String(description='时间'),
    'count': fields.Integer(description='告警数量')
})

violation_type_model = api.model('ViolationType', {
    'type': fields.String(description='违规类型'),
    'count': fields.Integer(description='数量'),
    'percentage': fields.Float(description='百分比')
})

traffic_flow_model = api.model('TrafficFlow', {
    'time': fields.String(description='时间'),
    'vehicle_count': fields.Integer(description='车辆数量')
})

time_distribution_model = api.model('TimeDistribution', {
    'hour': fields.Integer(description='小时'),
    'alert_count': fields.Integer(description='告警数量')
})

camera_stat_model = api.model('CameraStat', {
    'camera_id': fields.String(description='摄像头ID'),
    'camera_name': fields.String(description='摄像头名称'),
    'total_alerts': fields.Integer(description='告警总数'),
    'red_light': fields.Integer(description='闯红灯'),
    'wrong_way': fields.Integer(description='逆行'),
    'speeding': fields.Integer(description='超速'),
    'illegal_parking': fields.Integer(description='违停'),
    'vehicle_count': fields.Integer(description='车辆总数'),
    'flow_rate': fields.Float(description='平均流量')
})

statistics_response_model = api.model('StatisticsResponse', {
    'total_alerts': fields.Integer(description='总告警数'),
    'total_vehicles': fields.Integer(description='车辆总数'),
    'average_flow_rate': fields.Float(description='平均车流量'),
    'peak_flow_rate': fields.Float(description='峰值车流量'),
    'alert_trend': fields.List(fields.Nested(alert_trend_model)),
    'violation_types': fields.List(fields.Nested(violation_type_model)),
    'traffic_flow': fields.List(fields.Nested(traffic_flow_model)),
    'time_distribution': fields.List(fields.Nested(time_distribution_model)),
    'camera_stats': fields.List(fields.Nested(camera_stat_model))
})

@statistics_ns.route('/')
class Statistics(Resource):
    @api.doc(params={
        'time_range': '时间范围，支持24h、7d、30d或自定义时间范围',
        'start_time': '自定义开始时间（ISO格式）',
        'end_time': '自定义结束时间（ISO格式）',
        'camera_id': '摄像头ID，可选'
    })
    @api.marshal_with(statistics_response_model)
    def get(self):
        """获取统计数据"""
        try:
            # 获取查询参数
            time_range = request.args.get('time_range', '7d')
            start_time = request.args.get('start_time')
            end_time = request.args.get('end_time')
            camera_id = request.args.get('camera_id')
            
            # 计算时间范围
            end = datetime.now()
            if time_range == '24h':
                start = end - timedelta(hours=24)
            elif time_range == '7d':
                start = end - timedelta(days=7)
            elif time_range == '30d':
                start = end - timedelta(days=30)
            elif start_time and end_time:
                try:
                    start = datetime.fromisoformat(start_time)
                    end = datetime.fromisoformat(end_time)
                except ValueError:
                    return {'error': '无效的时间格式'}, 400
            else:
                return {'error': '无效的时间范围'}, 400
            
            # 获取统计数据
            statistics_data = get_statistics_data(start, end, camera_id)
            
            return statistics_data, 200
            
        except Exception as e:
            logger.error(f"获取统计数据失败: {str(e)}")
            return {'error': str(e)}, 500

@statistics_ns.route('/export')
class StatisticsExport(Resource):
    @api.doc(params={
        'time_range': '时间范围，支持24h、7d、30d或自定义时间范围',
        'start_time': '自定义开始时间（ISO格式）',
        'end_time': '自定义结束时间（ISO格式）'
    })
    def get(self):
        """导出统计数据为CSV格式"""
        try:
            # 获取查询参数
            time_range = request.args.get('time_range', '7d')
            start_time = request.args.get('start_time')
            end_time = request.args.get('end_time')
            
            # 计算时间范围
            end = datetime.now()
            if time_range == '24h':
                start = end - timedelta(hours=24)
            elif time_range == '7d':
                start = end - timedelta(days=7)
            elif time_range == '30d':
                start = end - timedelta(days=30)
            elif start_time and end_time:
                try:
                    start = datetime.fromisoformat(start_time)
                    end = datetime.fromisoformat(end_time)
                except ValueError:
                    return {'error': '无效的时间格式'}, 400
            else:
                return {'error': '无效的时间范围'}, 400
            
            # 获取统计数据
            statistics_data = get_statistics_data(start, end)
            
            # 转换为DataFrame
            df = pd.DataFrame(statistics_data['camera_stats'])
            
            # 转换为CSV
            csv_data = df.to_csv(index=False, encoding='utf-8-sig')
            
            # 设置响应头
            response = jsonify({
                'csv_data': csv_data,
                'filename': f'statistics_{start.strftime("%Y%m%d")}_{end.strftime("%Y%m%d")}.csv'
            })
            
            return response, 200
            
        except Exception as e:
            logger.error(f"导出统计数据失败: {str(e)}")
            return {'error': str(e)}, 500

@statistics_ns.route('/realtime')
class RealtimeStatistics(Resource):
    @api.doc(params={
        'camera_id': '摄像头ID，可选'
    })
    def get(self):
        """获取实时统计数据"""
        try:
            camera_id = request.args.get('camera_id')
            
            # 获取最近5分钟的实时数据
            end = datetime.now()
            start = end - timedelta(minutes=5)
            
            realtime_data = get_statistics_data(start, end, camera_id, realtime=True)
            
            return realtime_data, 200
            
        except Exception as e:
            logger.error(f"获取实时统计数据失败: {str(e)}")
            return {'error': str(e)}, 500